import express from 'express'
import multer from'multer'
import XLSX from 'xlsx'
import { PrismaClient } from'@prisma/client'

const prisma = new PrismaClient();

// 设置multer存储引擎
const storage = multer.memoryStorage();
const upload = multer({ storage });

const app = express();

app.post('/upload-excel', upload.single('file'), async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).send('没有上传文件');
    }

    // 使用xlsx解析Excel文件
    const workbook = XLSX.read(req.file.buffer, { type: 'buffer' });
    console.log('workbook',workbook)
    const sheetName = workbook.SheetNames[0];
    const sheet = workbook.Sheets[sheetName];

    // 将Excel数据转换为JSON对象数组
    const data = XLSX.utils.sheet_to_json(sheet);

    // 假设数据格式正确，直接插入数据库
    const excel = await req.db.product.createMany({
      data: data.map(row => ({
        name: row.name,
        age: parseInt(row.age),
        sex: row.sex,
        price: null,
        category: null,
        
      })),
    });
    res.send({success:true , message:'已成功上传文件并导入',data:excel});
  } catch (error) {
    console.error(error);
    res.fail({success:false , message:'文件上传失败'});
  }
});

export default app